package com.zmn.oms.zmn.business.impl.warranty;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.base.price.common.dto.item.ItemWarrantyDetailDRO;
import com.zmn.base.price.dubbo.interfaces.item.ItemWarrantyRemoteService;
import com.zmn.base.product.common.dto.product.erp.FaultWarrantyDRO;
import com.zmn.base.product.dubbo.interfaces.product.foreign.ProductTagsGroupForeignListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.business.interfaces.messageV1.SendOrderMessageService;
import com.zmn.oms.business.interfaces.messageV1.common.MessageGetSendInfoService;
import com.zmn.oms.business.interfaces.product.OrderProductExtendBService;
import com.zmn.oms.business.interfaces.warranty.OrderWarrantyBService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dto.MapDTO;
import com.zmn.oms.common.enums.WarrantyRuleEnum;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.work.modify.OrderWarrantyDTO;
import com.zmn.oms.model.dto.work.modify.OrderWarrantyUpdateDTO;
import com.zmn.oms.model.entity.product.OrderProductExtend;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.warranty.OrderWarranty;
import com.zmn.oms.model.entity.warranty.OrderWarrantyProduct;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.vo.warranty.WarrantyFaultVO;
import com.zmn.oms.model.vo.warranty.WarrantyListOrderVO;
import com.zmn.oms.model.vo.warranty.WarrantyListUserVO;
import com.zmn.oms.model.vo.warranty.WarrantyUserVO;
import com.zmn.oms.model.vo.work.modify.ZsOrderWarrantyProductVO;
import com.zmn.oms.model.vo.work.modify.ZsOrderWarrantyVO;
import com.zmn.oms.services.interfaces.product.OrderProductExtendService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.warranty.OrderWarrantyProductService;
import com.zmn.oms.services.interfaces.warranty.OrderWarrantyService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.warranty.ZsOrderWarrantyBService;
import com.zmn.base.plat.engine.common.constant.DubboConsts;
import com.zmn.uuc.dubbo.interfaces.user.UserThirdListRemoteService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：啄木鸟-保修卡实现
 *
 * @author heciqi
 * @date 2018/12/03 21:04
 */
public abstract class ZsOrderWarrantyBServiceImpl implements ZsOrderWarrantyBService {

    private static final Logger logger = LoggerFactory.getLogger(ZsOrderWarrantyBServiceImpl.class);

    @Autowired
    OrderWarrantyService orderWarrantyService;
    @Autowired
    OrderWarrantyBService orderWarrantyBService;
    @Autowired
    OrderWarrantyProductService orderWarrantyProductService;
    @Autowired
    OrderProductExtendBService orderProductExtendBService;
    @Autowired
    OrderProductExtendService orderProductExtendService;
    @Autowired
    OrderServiceItemService orderServiceItemService;
    @Autowired
    OrderWorkListBService orderWorkListBService;
    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    MessageGetSendInfoService messageGetSendInfoService;
    @Autowired
    SendOrderMessageService sendOrderMessageService;

    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private ProductTagsGroupForeignListRemoteService productTagsGroupForeignListRemoteService;
    @Reference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private UserThirdListRemoteService userThirdListRemoteService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private ItemWarrantyRemoteService itemWarrantyRemoteService;

    @Override
    public ZsOrderWarrantyVO findOrderWarrantyVo(Long orderId, Long workId) throws OmsBaseException {

        ZsOrderWarrantyVO orderWarrantyVO = new ZsOrderWarrantyVO();
        orderWarrantyVO.setOrderId(orderId);
        orderWarrantyVO.setWorkId(workId);

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);

        // 保修卡
        OrderWarranty orderWarranty = orderWarrantyService.findByOrderId(orderId);
        if (orderWarranty == null) {
            orderWarranty = new OrderWarranty();
            orderWarranty.setType(OrderConsts.ORDER_WARRANTY_TYPE_RECEIPT);
        }

        orderWarrantyVO.setMinDay(getMinWarrantyDay(orderWork));
        orderWarrantyVO.setModifyDay(orderWork.getStatus() >= OrderStatusConsts.WORK_STATUS_COMPLETE);
        orderWarrantyVO.setCode(orderWarranty.getCode());
        orderWarrantyVO.setType(orderWarranty.getType());
        Date grantTime = orderWarranty.getGrantTime();
        orderWarrantyVO.setGrant(grantTime != null ? GlobalConsts.YES : GlobalConsts.NO);
        orderWarrantyVO.setGrantTime(grantTime);

        // 查询订单产品 + 展开
        List<OrderProductExtend> orderProductExtendList = orderProductExtendBService.getOrderProductExtend(orderId);

        // 服务项
        List<OrderServiceItem> orderServiceItemList = orderServiceItemService.listByOrderId(orderId);
        Map<Long, List<OrderServiceItem>> serviceItemMap = orderServiceItemList.stream().collect(Collectors.groupingBy(OrderServiceItem::getProExtId));

        // 产品保修明细
        List<OrderWarrantyProduct> orderWarrantyProductList = orderWarrantyProductService.listByOrderId(orderId);
        Map<Long, OrderWarrantyProduct> warrantyProductMap = orderWarrantyProductList.stream()
                .collect(Collectors.toMap(OrderWarrantyProduct::getProExtId, orderWarrantyExtend -> orderWarrantyExtend));
        Map<Integer, List<MapDTO>> faultMap = Maps.newHashMap();

        List<ZsOrderWarrantyProductVO> orderWarrantyProductVOList = Lists.newArrayList();
        for (OrderProductExtend productExtend : orderProductExtendList) {
            ZsOrderWarrantyProductVO zsOrderWarrantyProductVO = new ZsOrderWarrantyProductVO();
            BeanMapper.copy(productExtend, zsOrderWarrantyProductVO);

            // 查询所有故障(已废弃 兼容历史工单数据)
            zsOrderWarrantyProductVO.setAllFault(getProductWarrantyItem(faultMap, productExtend.getProductId()));

            // 查询所有保修故障项
            zsOrderWarrantyProductVO.setWarrantyFault(getProductWarranty(productExtend.getProductId(), serviceItemMap.get(productExtend.getProExtId()), orderWork));

            // 产品信息
            zsOrderWarrantyProductVO.setProductId(productExtend.getProductId());
            zsOrderWarrantyProductVO.setProductName(productExtend.getProductName());
            zsOrderWarrantyProductVO.setStartTime(orderWarranty.getEffectiveTime());

            // 如果不存在则没选择保修项
            if (!warrantyProductMap.containsKey(productExtend.getProExtId())) {
                zsOrderWarrantyProductVO.setSelected(GlobalConsts.NO);
                orderWarrantyProductVOList.add(zsOrderWarrantyProductVO);
                continue;
            }

            // 已选项
            OrderWarrantyProduct orderWarrantyProduct = warrantyProductMap.get(productExtend.getProExtId());
            zsOrderWarrantyProductVO.setSelected(GlobalConsts.YES);
            // 兼容老数据
            if (StringUtils.isNotBlank(orderWarrantyProduct.getFault())) {
                List<MapDTO> mapDTOList = JSON.parseArray(orderWarrantyProduct.getFault(), MapDTO.class);
                zsOrderWarrantyProductVO.setFault(mapDTOList);
            } else {
                zsOrderWarrantyProductVO.setFault(Lists.newArrayList());
            }
            zsOrderWarrantyProductVO.setMonth(orderWarrantyProduct.getMonth());
            zsOrderWarrantyProductVO.setDay(orderWarrantyProduct.getDay());
            zsOrderWarrantyProductVO.setRemark(orderWarrantyProduct.getRemark());
            if (orderWarranty.getEffectiveTime() != null) {
                Date endTime;
                if (orderWarrantyProduct.getMonth() != null) {
                    // 此处历史数据兼容处理
                    endTime = DateUtil.addMonth(orderWarranty.getEffectiveTime(), orderWarrantyProduct.getMonth());
                } else {
                    endTime = DateUtil.addDays(orderWarranty.getEffectiveTime(), orderWarrantyProduct.getDay());
                }
                zsOrderWarrantyProductVO.setEndTime(endTime);
            }

            orderWarrantyProductVOList.add(zsOrderWarrantyProductVO);
        }

        // 新保修卡业务
        if (StringUtils.isBlank(orderWarranty.getCode())) {
            // 过滤保修项为空的数据
            orderWarrantyProductVOList = orderWarrantyProductVOList.stream().filter(item ->
                    CollectionUtils.isNotEmpty(item.getWarrantyFault().getAllFault())).collect(Collectors.toList());
        }

        orderWarrantyVO.setWarrantyProductVOList(orderWarrantyProductVOList);
        return orderWarrantyVO;
    }

    /**
     * 通过订单id查询保单信息
     *
     * @param orderId 订单id
     * @return 保单信息
     */
    @Override
    public WarrantyUserVO findWarrantyByOrderId(Long orderId) {
        return orderWarrantyBService.findWarrantyByOrderId(orderId);
    }

    /**
     * 通过多个订单id，查询订单保单信息
     *
     * @param orderIdList 订单id集合
     * @return 保单信息
     */
    @Override
    public List<WarrantyListOrderVO> listWarrantyByOrderIdList(List<Long> orderIdList) {
        return orderWarrantyBService.listWarrantyByOrderIdList(orderIdList);
    }

    /**
     * 通过订单id和保修code查询保单信息
     *
     * @param orderId 订单id
     * @param code    保修卡号
     * @return 保单信息
     */
    @Override
    public WarrantyUserVO findWarrantyDetailByOrderIdAndCode(Long orderId, String code) {
        return orderWarrantyBService.findWarrantyByOrderIdAndCode(orderId, code);
    }

    /**
     * 根据用户id获取保修卡列表
     *
     * @param userId 用户id
     * @return 保单信息
     */
    @Override
    public List<WarrantyListUserVO> listWarrantyByUserId(Long userId) {
        return orderWarrantyBService.listWarrantyByUserId(userId);
    }

    /**
     * 激活保修卡
     *
     * @param orderId 订单id
     * @return 激活结果
     */
    @Override
    public void activeWarranty(Long orderId) {
        orderWarrantyBService.activeWarranty(orderId);
    }

    /**
     * 领取保修卡
     *
     * @param orderId 订单id
     * @param userId
     * @return 激活结果
     */
    @Override
    public void takeWarranty(Long orderId, Long userId) {
        orderWarrantyBService.takeWarranty(orderId, userId);
    }

    /**
     * 生成保修卡
     *
     * @param warrDTO
     * @return
     */
    private OrderWarranty createOrderWarranty(OrderWarrantyDTO warrDTO) {
        OrderWarranty warranty = new OrderWarranty();
        warranty.setWarrId(warrDTO.getOrderId());
        warranty.setType(OrderConsts.ORDER_WARRANTY_TYPE_CARD);
        warranty.setStatus(OrderConsts.ORDER_WARRANTY_STATUS_INACTIVATED);
        warranty.setCreater(warrDTO.getOperator());
        warranty.setCreateTime(new Date());

        // region
        // 此处是师傅端APP发版期间的兼容处理 后期可以删除 by 2020-08-06
        if (NumberUtil.isNotNullOrZero(warrDTO.getMonth())) {
            warranty.setCode(StringUtil.getRandomsString(7));
        }
        //endRegion

        // 工单
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(warrDTO.getOrderId(), warrDTO.getWorkId());

        Long warrantyUserId = null;

        // A 上门用户（前置用户 > B 支付宝渠道 > C 下单用户绑定微信
        Long visitUserId = orderWork.getVisitUserId();
        boolean isAliChannel = Objects.equals(GlobalConsts.CHANNEL_ALIPAY_SERV_ID, orderWork.getChannelId()) || Objects.equals(GlobalConsts.CHANNEL_ALIPAY_APP_ID, orderWork.getChannelId());

        // 调用 uuc 接口，xiewenbing 2020-11-16
        //com.zmn.common.dto2.ResponseDTO<UserThirdBaseDRO> userThirdResponseDTO =userThirdListRemoteService.getThirdByUserIdAndChannel(orderWork.getUserId(), GlobalConsts.CHANNEL_WEIXIN_ID);
        // boolean supportC =userThirdResponseDTO.isSuccess() && StringUtil.isNotBlank(userThirdResponseDTO.getData().getOpenId());
        String uucOpenId = messageGetSendInfoService.getOrderUserRelationOpenId(warrDTO.getOrderId(), orderWork.getPlatWork(), warrantyUserId);
        boolean supportC = StringUtil.isNotBlank(uucOpenId);

        if (!NumberUtil.isNullOrZero(visitUserId)) {
            warrantyUserId = visitUserId;
        } else if (isAliChannel) {
            warrantyUserId = orderWork.getUserId();
        } else if (supportC) {
            warrantyUserId = orderWork.getUserId();
        }

        if (Objects.nonNull(warrantyUserId)) {
            warranty.setUserId(warrantyUserId);
            warranty.setGrantTime(DateUtil.getNow());
        } else {
            warranty.setUserId((long) GlobalConsts.NONE);
        }

        logger.info("#order#warranty#createorderwarranty orderid：{} visitUserId:{} isAliChannel: {}, uucOpenId:{} ",
                orderWork.getOrderId(), visitUserId, isAliChannel, uucOpenId);
        orderWarrantyService.insertWarranty(warranty);
        return warranty;
    }

    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_WARRANTY)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateWarranty(OrderWarrantyDTO warrDTO) throws OmsBaseException {
        // 查询保修卡
        OrderWarranty orderWarranty = orderWarrantyService.findByOrderIdByKeySrcMaster(warrDTO.getOrderId());

        if (orderWarranty == null) {
            orderWarranty = createOrderWarranty(warrDTO);
        }

        // region
        // 新老保修卡切换兼容处理
        if (StringUtils.isNotBlank(orderWarranty.getCode())) {
            if (NumberUtil.isNotNullOrZero(warrDTO.getDay())) {
                // 删订单保修项
                orderWarrantyService.deleteByOrderId(warrDTO.getOrderId());
                orderWarranty = createOrderWarranty(warrDTO);
            }
        }

        if (StringUtils.isBlank(orderWarranty.getCode())) {
            if (NumberUtil.isNotNullOrZero(warrDTO.getMonth())) {
                // 删订单保修项
                orderWarrantyService.deleteByOrderId(warrDTO.getOrderId());
                orderWarranty = createOrderWarranty(warrDTO);
            }
        }
        //endRegion

        // 校验工单产品项是否存在
        OrderProductExtend orderProductExtend = orderProductExtendService.findOrderProductExtendByKeySrcMaster(warrDTO.getOrderId(), warrDTO.getProExtId());
        if (orderProductExtend == null) {
            throw new OmsBaseException("产品项不存在");
        }

        // 删除
        orderWarrantyProductService.deleteByOrderIdAndProExtId(warrDTO.getOrderId(), warrDTO.getProExtId());

        // 先删除 后新增
        OrderWarrantyProduct orderWarrantyProduct = new OrderWarrantyProduct();
        orderWarrantyProduct.setWarrId(warrDTO.getOrderId());
        orderWarrantyProduct.setProExtId(warrDTO.getProExtId());
        orderWarrantyProduct.setCreater(warrDTO.getOperator());
        orderWarrantyProduct.setMonth(warrDTO.getMonth());

        orderWarrantyProduct.setRuleId(warrDTO.getRuleId());
        orderWarrantyProduct.setDay(warrDTO.getDay());
        if (NumberUtil.isNotNullOrZero(warrDTO.getAddDay())) {
            orderWarrantyProduct.setDay(warrDTO.getAddDay());
            warrDTO.setDay(warrDTO.getAddDay());
        }

        // 兼容老逻辑判断 后期 if条件可以删除
        if (NumberUtil.isNullOrZero(warrDTO.getMonth())) {
            orderWarrantyProduct.setCode(StringUtil.getRandomsString(7));
        }

        List<MapDTO> fault = warrDTO.getFault();
        if (fault != null) {
            orderWarrantyProduct.setFault(JSON.toJSONString(fault));
        }

        orderWarrantyProduct.setProductId(warrDTO.getProductId());
        orderWarrantyProduct.setProductName(warrDTO.getProductName());
        orderWarrantyProduct.setRemark(warrDTO.getRemark());

        if (orderWarranty.getEffectiveTime() != null) {
            if (NumberUtil.isNotNullOrZero(warrDTO.getMonth())) {
                // 此处是师傅端APP发版期间的兼容处理 后期可以删除 by 2020-08-06
                orderWarrantyProduct.setExpiredTime(DateUtil.addMonth(orderWarranty.getEffectiveTime(), warrDTO.getMonth()));
            } else {
                orderWarrantyProduct.setExpiredTime(DateUtil.addDays(orderWarranty.getEffectiveTime(), warrDTO.getDay()));
            }
        }

        orderWarrantyProductService.insertAll(Lists.newArrayList(orderWarrantyProduct));

        // 当所有保修产品保修项是仅上门的时候 修改类型为收据
        boolean unOnlyVisit = false;
        do {

            // 当前故障选项
            if (warrDTO.getFault() != null) {
                // TODO lujia 待优化 汉字匹配
                unOnlyVisit = warrDTO.getFault().stream().anyMatch(e -> !Objects.equals("仅上门", e.getMapName()));
                if (unOnlyVisit) {
                    break;
                }
            }

            // 其他产品故障选项
            List<OrderWarrantyProduct> orderWarrantyProducts = orderWarrantyProductService.listByOrderId(warrDTO.getOrderId());
            if (orderWarrantyProducts != null) {
                for (OrderWarrantyProduct warrantyProduct : orderWarrantyProducts) {
                    String warrFault = warrantyProduct.getFault();
                    if (StringUtil.isNotBlank(warrFault)) {
                        List<MapDTO> mapDTOList = JSON.parseArray(warrFault, MapDTO.class);
                        // TODO lujia 待优化 汉字匹配
                        unOnlyVisit = mapDTOList.stream().anyMatch(e -> !Objects.equals("仅上门", e.getMapName()));
                        if (unOnlyVisit) {
                            break;
                        }
                    }
                }
            }

            if (NumberUtil.isNotNullOrZero(warrDTO.getDay()) || NumberUtil.isNotNullOrZero(warrDTO.getAddDay())) {
                unOnlyVisit = true;
                break;
            }

            // 当前其他故障
            if (StringUtil.isNotBlank(warrDTO.getRemark()) && warrDTO.getMonth() != null && warrDTO.getMonth() > 0) {
                unOnlyVisit = true;
                break;
            }

        } while (false);

        int type = unOnlyVisit ? OrderConsts.ORDER_WARRANTY_TYPE_CARD : OrderConsts.ORDER_WARRANTY_TYPE_RECEIPT;
        orderWarrantyService.updateWarrantyType(warrDTO.getOrderId(), type);
    }

    /**
     * 查询工单产品保修项目（老）
     *
     * @param faultMap
     * @param productId
     * @return
     * @throws OmsBaseException
     */
    private List<MapDTO> getProductWarrantyItem(Map<Integer, List<MapDTO>> faultMap, Integer productId) throws OmsBaseException {


        List<MapDTO> mapDTOList = Lists.newArrayList();

        // 获取该产品所有的保修项
        if (faultMap.containsKey(productId)) {
            List<MapDTO> mapDTOS = faultMap.get(productId);
            return mapDTOS;
        }

        // 调用dubbo服务查询产品保修项目
        ResponseDTO<List<FaultWarrantyDRO>> servSubsidiaryItemDROResponseDTO = productTagsGroupForeignListRemoteService.listWarrantyByProductId(productId);
        if (!servSubsidiaryItemDROResponseDTO.isSuccess()) {
            logger.error("#work#warranty {} 产品获取保修卡失败", productId);
            return mapDTOList;
        }

        // 过滤出产品保修项
        List<FaultWarrantyDRO> warrantyItem = servSubsidiaryItemDROResponseDTO.getData();
        if (warrantyItem == null || warrantyItem.isEmpty()) {
            logger.error("#work#warranty {} 产品获取保修卡为空", productId);
        }

        // 组合
        warrantyItem.forEach(itemDRO -> {
            MapDTO mapDTO = new MapDTO();
            mapDTO.setMapId(itemDRO.getItemId());
            mapDTO.setMapName(itemDRO.getName());
            mapDTOList.add(mapDTO);
        });
        faultMap.put(productId, mapDTOList);

        return mapDTOList;
    }


    /**
     * 查询工单产品保修项目（新）
     *
     * @param orderWork
     * @param productId
     * @return
     * @throws OmsBaseException
     */
    private WarrantyFaultVO getProductWarranty(Integer productId, List<OrderServiceItem> orderServiceItemList, OrderWork orderWork) throws OmsBaseException {

        WarrantyFaultVO warrantyFaultVO = new WarrantyFaultVO();
        List<MapDTO> mapDTOList = Lists.newArrayList();

        productId = NumberUtil.isNullOrZero(productId) ? orderWork.getProductId() : productId;
        Set<Integer> itemIds = orderServiceItemList.stream().map(OrderServiceItem::getServItemId).collect(Collectors.toSet());

        // 后台产品为空
        if (NumberUtil.isNullOrZero(productId)) {
            logger.debug("#work#warranty productId={} 产品获取保修卡后台产品为空", productId);
            return warrantyFaultVO;
        }
        // 服务项为空
        if (CollectionUtils.isEmpty(itemIds)) {
            logger.debug("#work#warranty itemIds={} 产品获取保修卡服务项为空", itemIds);
            return warrantyFaultVO;
        }

        logger.info("订单号={},获取保修卡信息入参 plat={}，product={}，itemIds={}", orderWork.getOrderId(), orderWork.getPlatWork(), productId, itemIds);//10001, Lists.newArrayList(1719, 1695),
        ResponseDTO<ItemWarrantyDetailDRO> resp = itemWarrantyRemoteService.getByProductIdAndItemIdList(productId, Lists.newArrayList(itemIds));
        logger.info("订单号={},获取保修卡信息出参 {}", orderWork.getOrderId(), JSON.toJSONString(resp));
        if (Objects.isNull(resp) || !resp.isSuccess()) {
            logger.debug("#work#warranty {} 产品获取保修卡失败", productId);
            return warrantyFaultVO;
        }

        ItemWarrantyDetailDRO warrantyItem = resp.getData();
        if (warrantyItem == null || CollectionUtils.isEmpty(warrantyItem.getContentOptionList())) {
            logger.debug("#work#warranty {} 产品获取保修卡为空", productId);
            return warrantyFaultVO;
        }

        // 组合故障信息
        warrantyItem.getContentOptionList().forEach(itemDRO -> {
            MapDTO mapDTO = new MapDTO();
            mapDTO.setMapId(itemDRO.getValue());
            mapDTO.setMapName(itemDRO.getLabel());
            mapDTOList.add(mapDTO);
        });

        // 处理保修时间排序
        List<String> days = Lists.newArrayList(warrantyItem.getDays());
        List<Integer> daysInteger = days.stream().map(Integer::parseInt).distinct().collect(Collectors.toList());
        Collections.sort(daysInteger);
        warrantyFaultVO.setAllFault(mapDTOList);
        warrantyFaultVO.setDays(daysInteger);
        warrantyFaultVO.setRuleId(warrantyItem.getWarrantyType());
        warrantyFaultVO.setRuleName(WarrantyRuleEnum.of(warrantyItem.getWarrantyType()).getName());
        return warrantyFaultVO;
    }

    /**
     * 获取完成工单保修卡当前保修天数；
     *
     * @param orderWork
     * @return
     */
    private Integer getMinWarrantyDay(OrderWork orderWork) {
        Long minDay = 0L;
        // 工单状态大于等于完成状态
        if (orderWork.getStatus() >= OrderStatusConsts.WORK_STATUS_COMPLETE) {
            // 保修天数需> = 当前时间-完成时间
            minDay = DateUtil.getTimespan(DateUtil.getDateStart(orderWork.getCompleteTime()), DateUtil.getDateStart(new Date()), DateUtil.UNIT_DAY) + 1;
        }
        return minDay.intValue();
    }

    @Override
    public void deleteWarranty(OrderWarrantyDTO orderWarrantyDTO) {
        orderWarrantyProductService.deleteByOrderIdAndProExtId(orderWarrantyDTO.getOrderId(), orderWarrantyDTO.getProExtId());
    }

    @Override
    public Map<Long, Integer> isExistWarrantyInfoMap(Long orderId, Long workId) {
        return orderWarrantyBService.isExistWarrantyInfoMap(orderId, workId);
    }

    @Override
    public void autoAddWarrantyDay(Long orderId, Long workId) {
        /*
         * 原单首次返修
         * 1.判断该单未返修单，取返修Id即为原单订单号
         * 2.判断原单二次返修进行拦截 return
         * 3.获取原单信息，判断是否存在返修卡
         * 4.根据订单服务项目获取延保信息
         * 5.原单多张保修卡，仅延其中一张保修卡
         * 6.发送延保消息给用户 微信 > 短信
         */
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        if (!Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REWORK) || NumberUtil.isNullOrZero(orderWork.getReworkId())) {
            return;
        }

        // 原单返修一次
        OrderWorkQuery query = new OrderWorkQuery();
        query.setReworkId(orderWork.getReworkId());
        query.setWorkType(Lists.newArrayList(OrderConsts.ORDER_TYPE_REWORK));
        Integer orderWorkCount = orderWorkListBService.countOrderWorkByQuery(query);
        if (orderWorkCount > 1) {
            return;
        }

        // 后台产品不能为空
        if (NumberUtil.isNullOrZero(orderWork.getProductId())) {
            return;
        }

        // 订单保修卡信息
        OrderWarranty orderWarranty = orderWarrantyService.findByOrderId(orderWork.getReworkId());
        if (orderWarranty == null) {
            return;
        }

        // 获取原单的服务项
        List<OrderServiceItem> orderServiceItemList = orderServiceItemService.listByOrderId(orderWork.getReworkId());
        Set<Integer> itemIds = orderServiceItemList.stream().map(OrderServiceItem::getServItemId).collect(Collectors.toSet());
        // 获取保修卡延保信息
        logger.info("#warranty#订单号={}, 获取保修卡延保信息入参 plat={}，product={}，itemIds={}", orderWork.getOrderId(), orderWork.getPlatWork(), orderWork.getProductId(), itemIds);
        com.zmn.common.dto2.ResponseDTO<ItemWarrantyDetailDRO> resp = itemWarrantyRemoteService.getByProductIdAndItemIdList(orderWork.getProductId(), Lists.newArrayList(itemIds));
        logger.info("#warranty#订单号={}, 获取保修卡延保信息出参 {}", orderWork.getOrderId(), JSON.toJSONString(resp));
        ItemWarrantyDetailDRO warrantyInfo = resp.getData();
        if (!resp.isSuccess() || Objects.isNull(warrantyInfo)) {
            return;
        }

        // 是否延保
        if (!Objects.equals(warrantyInfo.getExtendType(), GlobalConsts.YES)) {
            logger.info("#warranty#订单号={}, 是否延长保修【否】", orderWork.getOrderId());
            return;
        }
        //  延保天数
        Integer addDay = warrantyInfo.getExtendedDuetime();
        if (NumberUtil.isNullOrZero(addDay)) {
            logger.info("#warranty#订单号={}, 延保天数不合法", orderWork.getOrderId());
            return;
        }

        //  获取原单保修卡信息
        List<OrderWarrantyProduct> warrantyProducts = orderWarrantyProductService.listByOrderId(orderWork.getReworkId());

        // 保修卡为空 或 非保修卡不处理
        if (CollectionUtils.isEmpty(warrantyProducts) || !Objects.equals(OrderConsts.ORDER_WARRANTY_TYPE_CARD, orderWarranty.getType())) {
            return;
        }

        // 获取最大保修时长
        Optional<OrderWarrantyProduct> max = warrantyProducts.stream().max(Comparator.comparing(OrderWarrantyProduct::getExpiredTime));
        if (!max.isPresent()) {
            return;
        }

        // 判断原单保修卡是否过期，返修单下单时间 = < 保修卡截止日期（最大）即 未过期
        Date maxExpiredTime = max.get().getExpiredTime();

        //  保修卡过期截止日期 < 返修单下单时间，即过期，不延保
        if (maxExpiredTime.before(orderWork.getReceiveTime())) {
            return;
        }

        // 多张保修卡选其中一张保修卡，进行延保
        OrderWarrantyProduct warrantyProduct = max.get();
        Date expiredTime = DateUtil.addDays(maxExpiredTime, addDay);
        OrderWarrantyUpdateDTO warrUpdateDTO = new OrderWarrantyUpdateDTO();
        warrUpdateDTO.setOrderId(warrantyProduct.getWarrId());
        warrUpdateDTO.setWorkId(warrantyProduct.getWarrId());
        warrUpdateDTO.setAddDay(addDay);
        warrUpdateDTO.setOldDay(warrantyProduct.getDay());
        warrUpdateDTO.setOldExpiredTime(maxExpiredTime);
        warrUpdateDTO.setExpiredTime(expiredTime);
        warrUpdateDTO.setProId(warrantyProduct.getProId());
        warrUpdateDTO.setReWorkId(orderId);
        warrUpdateDTO.setWarrId(warrantyProduct.getWarrId());
        warrUpdateDTO.setCode(warrantyProduct.getCode());
        orderWarrantyBService.autoAddWarrantyDay(warrUpdateDTO);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createQuotation3Warranty(OrderWork orderWork, OrderWarrantyDTO warrDTO) {

        // 删除
        orderWarrantyService.deleteByOrderId(warrDTO.getOrderId());
        orderWarrantyProductService.deleteByOrderId(warrDTO.getOrderId());

        OrderWarranty warranty = new OrderWarranty();
        warranty.setWarrId(warrDTO.getOrderId());
        warranty.setType(OrderConsts.ORDER_WARRANTY_TYPE_CARD);
        warranty.setStatus(OrderConsts.ORDER_WARRANTY_STATUS_INACTIVATED);
        warranty.setCreater(warrDTO.getOperator());
        warranty.setCreateTime(new Date());

        // 工单
        if (Objects.isNull(orderWork)) {
            orderWork = orderWorkService.findOrderWorkByKey(warrDTO.getOrderId(), warrDTO.getWorkId());
        }

        Long warrantyUserId = null;

        // A 上门用户（前置用户 > B 支付宝渠道 > C 下单用户绑定微信
        Long visitUserId = orderWork.getVisitUserId();
        boolean isAliChannel = Objects.equals(GlobalConsts.CHANNEL_ALIPAY_SERV_ID, orderWork.getChannelId()) || Objects.equals(GlobalConsts.CHANNEL_ALIPAY_APP_ID, orderWork.getChannelId());

        // 调用 uuc 接口，xiewenbing 2020-11-16
        //com.zmn.common.dto2.ResponseDTO<UserThirdBaseDRO> userThirdResponseDTO =userThirdListRemoteService.getThirdByUserIdAndChannel(orderWork.getUserId(), GlobalConsts.CHANNEL_WEIXIN_ID);
        // boolean supportC =userThirdResponseDTO.isSuccess() && StringUtil.isNotBlank(userThirdResponseDTO.getData().getOpenId());
        String uucOpenId = messageGetSendInfoService.getOrderUserRelationOpenId(warrDTO.getOrderId(), orderWork.getPlatWork(), warrantyUserId);
        boolean supportC = StringUtil.isNotBlank(uucOpenId);

        if (!NumberUtil.isNullOrZero(visitUserId)) {
            warrantyUserId = visitUserId;
        } else if (isAliChannel) {
            warrantyUserId = orderWork.getUserId();
        } else if (supportC) {
            warrantyUserId = orderWork.getUserId();
        }

        if (Objects.nonNull(warrantyUserId)) {
            warranty.setUserId(warrantyUserId);
            warranty.setGrantTime(DateUtil.getNow());
        } else {
            warranty.setUserId((long) GlobalConsts.NONE);
        }

        // region
        if (NumberUtil.isNotNullOrZero(warrDTO.getDay())) {
//            warranty.setCode(StringUtil.getRandomsString(7));
        }
        //endRegion

        logger.info("#order#warranty#createQuotation3OrderWarranty orderid：{} visitUserId:{} isAliChannel: {}, uucOpenId:{} ",
                orderWork.getOrderId(), visitUserId, isAliChannel, uucOpenId);
        orderWarrantyService.insertWarranty(warranty);

        // 新增
        OrderWarrantyProduct orderWarrantyProduct = new OrderWarrantyProduct();
        orderWarrantyProduct.setWarrId(warrDTO.getOrderId());
        orderWarrantyProduct.setProExtId(warrDTO.getProExtId());
        orderWarrantyProduct.setCreater(warrDTO.getOperator());
        orderWarrantyProduct.setMonth(warrDTO.getMonth());

        orderWarrantyProduct.setRuleId(warrDTO.getRuleId());
        orderWarrantyProduct.setDay(warrDTO.getDay());
        if (NumberUtil.isNotNullOrZero(warrDTO.getAddDay())) {
            orderWarrantyProduct.setDay(warrDTO.getAddDay());
            warrDTO.setDay(warrDTO.getAddDay());
        }

        List<MapDTO> fault = warrDTO.getFault();
        if (fault != null) {
            orderWarrantyProduct.setFault(JSON.toJSONString(fault));
        }

        orderWarrantyProduct.setProductId(warrDTO.getProductId());
        orderWarrantyProduct.setProductName(warrDTO.getProductName());
        orderWarrantyProduct.setRemark(warrDTO.getRemark());
        orderWarrantyProduct.setCode(StringUtil.getRandomsString(7));

        orderWarrantyProductService.insertAll(Lists.newArrayList(orderWarrantyProduct));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWarranty(Long orderId) {
        orderWarrantyService.deleteByOrderId(orderId);
        orderWarrantyProductService.deleteByOrderId(orderId);
    }
}